<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="page-title">权限管理</h1>
        <div class="breadcrumb-container">
          <router-link to="/" class="link link-hover">首页</router-link>
          <span class="mx-2">/</span>
          <span>系统管理</span>
          <span class="mx-2">/</span>
          <span>权限管理</span>
        </div>
      </div>
      <div class="btn-group">
        <button
          class="btn btn-primary gap-2"
          @click="handleNewPermission"
        >
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
          </svg>
          新建权限
        </button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="card bg-base-100 shadow-lg mb-6">
      <div class="card-body">
        <div class="flex flex-wrap gap-4">
          <div class="form-control flex-1 min-w-[200px]">
            <label class="label">
              <span class="label-text">权限名称</span>
            </label>
            <input
              type="text"
              v-model="searchForm.name"
              placeholder="请输入权限名称"
              class="input input-bordered"
            />
          </div>
          <div class="form-control flex-1 min-w-[200px]">
            <label class="label">
              <span class="label-text">权限代码</span>
            </label>
            <input
              type="text"
              v-model="searchForm.code"
              placeholder="请输入权限代码"
              class="input input-bordered"
            />
          </div>
          <div class="form-control flex-1 min-w-[200px]">
            <label class="label">
              <span class="label-text">模块</span>
            </label>
            <select
              v-model="searchForm.module"
              class="select select-bordered"
            >
              <option value="">全部</option>
              <option v-for="module in modules" :key="module" :value="module">
                {{ module }}
              </option>
            </select>
          </div>
          <div class="form-control flex-none self-end">
            <button
              class="btn btn-primary"
              :class="{ loading: isSearching }"
              @click="handleSearch"
            >
              搜索
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 权限列表 -->
    <div class="card bg-base-100 shadow-lg">
      <div class="card-body">
        <div class="overflow-x-auto">
          <table class="table w-full">
            <thead>
              <tr>
                <th>权限名称</th>
                <th>权限代码</th>
                <th>模块</th>
                <th>描述</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="permission in permissions" :key="permission.id">
                <td>{{ permission.name }}</td>
                <td>{{ permission.code }}</td>
                <td>{{ permission.module }}</td>
                <td>{{ permission.description }}</td>
                <td>{{ formatDate(permission.createdAt) }}</td>
                <td>
                  <div class="btn-group">
                    <button
                      class="btn btn-sm btn-ghost"
                      @click="handleEdit(permission)"
                    >
                      编辑
                    </button>
                    <button
                      class="btn btn-sm btn-ghost text-error"
                      @click="handleDelete(permission)"
                    >
                      删除
                    </button>
                  </div>
                </td>
              </tr>
              <tr v-if="permissions.length === 0">
                <td colspan="6" class="text-center py-4">暂无数据</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="flex justify-between items-center mt-4">
          <div class="text-sm text-base-content/70">
            共 {{ total }} 条数据
          </div>
          <div class="btn-group">
            <button
              class="btn btn-sm"
              :class="{ 'btn-disabled': page === 1 }"
              @click="handlePageChange(page - 1)"
            >
              上一页
            </button>
            <button class="btn btn-sm">{{ page }} / {{ totalPages }}</button>
            <button
              class="btn btn-sm"
              :class="{ 'btn-disabled': page === totalPages }"
              @click="handlePageChange(page + 1)"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 权限表单对话框 -->
    <dialog
      ref="formDialog"
      class="modal"
      :class="{ 'modal-open': showFormDialog }"
    >
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">
          {{ isEdit ? '编辑权限' : '新建权限' }}
        </h3>
        <div class="space-y-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">权限名称</span>
            </label>
            <input
              type="text"
              v-model="form.name"
              placeholder="请输入权限名称"
              class="input input-bordered"
              :class="{ 'input-error': errors.name }"
            />
            <label class="label" v-if="errors.name">
              <span class="label-text-alt text-error">{{ errors.name }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">权限代码</span>
            </label>
            <input
              type="text"
              v-model="form.code"
              placeholder="请输入权限代码"
              class="input input-bordered"
              :class="{ 'input-error': errors.code }"
            />
            <label class="label" v-if="errors.code">
              <span class="label-text-alt text-error">{{ errors.code }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">模块</span>
            </label>
            <select
              v-model="form.module"
              class="select select-bordered"
              :class="{ 'select-error': errors.module }"
            >
              <option value="">请选择模块</option>
              <option v-for="module in modules" :key="module" :value="module">
                {{ module }}
              </option>
            </select>
            <label class="label" v-if="errors.module">
              <span class="label-text-alt text-error">{{ errors.module }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">描述</span>
            </label>
            <textarea
              v-model="form.description"
              placeholder="请输入权限描述"
              class="textarea textarea-bordered h-24"
              :class="{ 'textarea-error': errors.description }"
            ></textarea>
            <label class="label" v-if="errors.description">
              <span class="label-text-alt text-error">{{ errors.description }}</span>
            </label>
          </div>
        </div>
        <div class="modal-action">
          <button
            class="btn btn-ghost"
            @click="closeFormDialog"
          >
            取消
          </button>
          <button
            class="btn btn-primary"
            :class="{ loading: isSaving }"
            @click="handleSave"
          >
            保存
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>

    <!-- 删除确认对话框 -->
    <dialog
      ref="deleteDialog"
      class="modal"
      :class="{ 'modal-open': showDeleteDialog }"
    >
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">删除权限</h3>
        <p>确定要删除权限"{{ selectedPermission?.name }}"吗？此操作不可恢复。</p>
        <div class="modal-action">
          <button
            class="btn btn-ghost"
            @click="closeDeleteDialog"
          >
            取消
          </button>
          <button
            class="btn btn-error"
            :class="{ loading: isDeleting }"
            @click="confirmDelete"
          >
            删除
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { SystemService, type Permission } from '@/api/services'
import { useLoadingStore } from '@/stores/loading'
import { useToast } from '@/composables/useToast'

const loadingStore = useLoadingStore()
const toast = useToast()

// 状态
const isSearching = ref(false)
const isSaving = ref(false)
const isDeleting = ref(false)
const showFormDialog = ref(false)
const showDeleteDialog = ref(false)
const isEdit = ref(false)
const selectedPermission = ref<Permission | null>(null)

// 数据
const permissions = ref<Permission[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = 10

const totalPages = computed(() => Math.ceil(total.value / pageSize))

const modules = [
  '用户管理',
  '数据同步',
  '判定记录',
  '冥币管理',
  '日志管理',
  '系统管理',
]

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  module: '',
})

// 编辑表单
interface Form {
  name: string
  code: string
  module: string
  description: string
}

interface FormErrors {
  name?: string
  code?: string
  module?: string
  description?: string
}

const form = reactive<Form>({
  name: '',
  code: '',
  module: '',
  description: '',
})

const errors = reactive<FormErrors>({})

// 方法
const loadPermissions = async () => {
  try {
    isSearching.value = true
    const { items, total: totalCount } = await SystemService.getPermissions({
      ...searchForm,
      page: page.value,
      pageSize,
    })
    permissions.value = items
    total.value = totalCount
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isSearching.value = false
  }
}

const handleSearch = () => {
  page.value = 1
  loadPermissions()
}

const handlePageChange = (newPage: number) => {
  page.value = newPage
  loadPermissions()
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleString()
}

const resetForm = () => {
  form.name = ''
  form.code = ''
  form.module = ''
  form.description = ''
  errors.name = ''
  errors.code = ''
  errors.module = ''
  errors.description = ''
}

const handleNewPermission = () => {
  isEdit.value = false
  resetForm()
  showFormDialog.value = true
}

const handleEdit = (permission: Permission) => {
  isEdit.value = true
  Object.assign(form, permission)
  showFormDialog.value = true
}

const closeFormDialog = () => {
  showFormDialog.value = false
}

const validateForm = () => {
  let isValid = true
  errors.name = ''
  errors.code = ''
  errors.module = ''
  errors.description = ''

  if (!form.name) {
    errors.name = '请输入权限名称'
    isValid = false
  }

  if (!form.code) {
    errors.code = '请输入权限代码'
    isValid = false
  }

  if (!form.module) {
    errors.module = '请选择模块'
    isValid = false
  }

  if (!form.description) {
    errors.description = '请输入权限描述'
    isValid = false
  }

  return isValid
}

const handleSave = async () => {
  if (!validateForm()) {
    toast.warning('请检查表单填写是否正确')
    return
  }

  try {
    isSaving.value = true
    if (isEdit.value) {
      await SystemService.updatePermission(selectedPermission.value!.id, form)
      toast.success('更新成功')
    } else {
      await SystemService.createPermission(form)
      toast.success('创建成功')
    }
    closeFormDialog()
    loadPermissions()
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isSaving.value = false
  }
}

const handleDelete = (permission: Permission) => {
  selectedPermission.value = permission
  showDeleteDialog.value = true
}

const closeDeleteDialog = () => {
  showDeleteDialog.value = false
  selectedPermission.value = null
}

const confirmDelete = async () => {
  if (!selectedPermission.value) return

  try {
    isDeleting.value = true
    await SystemService.deletePermission(selectedPermission.value.id)
    toast.success('删除成功')
    closeDeleteDialog()
    loadPermissions()
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isDeleting.value = false
  }
}

// 初始化
loadPermissions()
</script>
